import React from 'react';
import ReactEcharts from 'echarts-for-react';
import { Modal } from 'antd';
import $ from 'jquery';
let xAxisValue;
let charts;
let storeChartStatus = {
  dataZoomXStart: 0,
  dataZoomXEnd: 100,
  dataZoomXStartValue: 0,
  dataZoomXEndValue: 0,
  dataZoomYStart: 10,
  dataZoomYEnd: 90,
};
let coordY = {
  "offbed": 1000,
  "apnea": 1500,
}

let lineColor = {
  "brest": "blue",
  "head": "red",
  "offbed": "pink",
  "apnea": "green",
}

let markColor = {
  "offbed": 'pink',
  "apnea": 'green',
}

class DrawPanel extends React.Component {
  state = {
    chartValue: '',
    eventName: '',
    coord: '',
    axisId: '',
    offbedMarkPoint: [],
    apneaMarkPoint: [],
    selectValue: '',
    dataZoomXStart: 0,
    dataZoomXEnd: 100,
    dataZoomXStartValue: 0,
    dataZoomXEndValue: 0,
    dataZoomYStart: 10,
    dataZoomYEnd: 90,
    markItem: [],
    tagFilePath: '',
    seriesId: '',
    markPointsObj: [],
  }

  componentDidMount() {
    $('#drawPanel').off('contextmenu').on('contextmenu', this.clickCharts);
  }

  componentWillReceiveProps(nextProps) {
    const offbedMarkPoint = [];
    const apneaMarkPoint = [];
    if (charts && (((this.props.sidePanelShow === false) && (nextProps.sidePanelShow === true)) || ((this.props.filterPanelShow === false) && (nextProps.filterPanelShow === true)))) {
      charts.resize({
        "width": document.body.clientWidth - 480 + 'px',
        "height": "auto"
      });
    } else if (charts && (((this.props.sidePanelShow === true) && (nextProps.sidePanelShow === false)) || ((this.props.filterPanelShow === true) && (nextProps.filterPanelShow === false)))) {
      charts.resize({
        "width": "auto",
        "height": "auto"
      });
    }
    const markPoints = (nextProps.tagFilePath && nextProps.jsonTree[nextProps.tagFilePath]) ? nextProps.jsonTree[nextProps.tagFilePath].event : [];
    if (markPoints.length > 0) {
      markPoints.forEach(element => {
        if (element.eventName === '离床') {
          if (element.timeStart) {
            const cpTimeStart = Object.assign({}, { "eventName": element.eventName,  coord: [element.timeStart, coordY.offbed], "itemStyle": {
              "color": markColor.offbed,
            }});
            offbedMarkPoint.push(cpTimeStart);
          }
          if (element.timeEnd) {
            const cpTimeEnd = Object.assign({}, { "eventName": element.eventName,  coord: [element.timeEnd, coordY.offbed], "itemStyle": {
              "color":  markColor.offbed,
            }});
            offbedMarkPoint.push(cpTimeEnd)
          }

        } else if (element.eventName === '呼吸暂停') {
          if (element.timeStart) {
            const cpTimeStart = Object.assign({}, { "eventName": element.eventName,  coord: [element.timeStart, coordY.apnea], "itemStyle": {
              "color": markColor.apnea,
            }});
            apneaMarkPoint.push(cpTimeStart);
          }
          if (element.timeEnd) {
            const cpTimeEnd = Object.assign({}, { "eventName": element.eventName,  coord: [element.timeEnd, coordY.apnea], "itemStyle": {
              "color": markColor.apnea,
            }});
            apneaMarkPoint.push(cpTimeEnd);
          }
        }
      });
    }
    //console.log(this.state.tagFilePath, nextProps.tagFilePath, this.state.tagFilePath !== nextProps.tagFilePath)
    if (this.state.tagFilePath !== nextProps.tagFilePath) {
      storeChartStatus = {
        dataZoomXStart: 0,
        dataZoomXEnd: 100,
        dataZoomXStartValue: 0,
        dataZoomXEndValue: 0,
        dataZoomYStart: 10,
        dataZoomYEnd: 90,
      };
    }
    this.setState({
      eventName: nextProps.pickEvent,
      markPointsObj: markPoints,
      markItem: nextProps.markItem,
      tagFilePath: nextProps.tagFilePath,
      dataZoomXStart: storeChartStatus.dataZoomXStart,
      dataZoomXEnd: storeChartStatus.dataZoomXEnd,
      dataZoomXStartValue: storeChartStatus.dataZoomXStartValue,
      dataZoomXEndValue: storeChartStatus.dataZoomXEndValue,
      dataZoomYStart: storeChartStatus.dataZoomYStart,
      dataZoomYEnd: storeChartStatus.dataZoomYEnd,
      offbedMarkPoint,
      apneaMarkPoint,
    })
  }

  handleOk = (timeStamp) => {
    this.props.insertMarkPoint({
      data: timeStamp,
      path: this.state.tagFilePath,
    });
  }

  handleCancel = (e) => {
    this.setState({
      chartValue: '',
      eventName: '',
      coord: '',
      selectValue: '',
      axisId: '',
    });
  }

  handleChange = (value) => {
    this.setState({ selectValue: value });
  }

  getOption = () => {
    if (charts) {
      charts.clear();
    }
    const legendData = [
      {name: '胸部曲线', icon: 'rec', textStyle: {color: '#fff'}},
      {name: '头部曲线', icon: 'rec', textStyle: {color: '#fff'}},
    ];
    const seriesData = [
      {
        data: this.props.plotChestData,
        id: 'brestAxis',
        type: 'line',
        showSymbol: false,
        symbolSize: 8,
        cusor: 'pointer',
        name:'胸部曲线',
        lineStyle: {
          color: lineColor.brest,
          width: 1,
        },
        itemStyle: {
          color: lineColor.brest,
        },
      },{
        data: this.props.plotHeadData,
        type: 'line',
        id: 'headAxis',
        cusor: 'pointer',
        showSymbol: false,
        symbolSize: 8,
        name:'头部曲线',
        lineStyle: {
          color: lineColor.head,
          width: 1,
        },
        itemStyle: {
          color: lineColor.head,
        },
      },
    ];
    if (this.state.offbedMarkPoint.length) {
      legendData.push({name: '离床', icon: 'rec', textStyle: {color: '#fff'}});
      seriesData.push({
        data: [],
        type: 'line',
        id: 'offbedAxis',
        cusor: 'pointer',
        showSymbol: false,
        symbolSize: 8,
        name:'离床',
        lineStyle: {
          color: lineColor.offbed,
          width: 1,
        },
        itemStyle: {
          color: lineColor.offbed,
        },
        markPoint: {
          symbol: 'pin',
          symbolSize: 15,
          data: this.state.offbedMarkPoint
        },
        markLine: {
          slient: true,
          label: {
            show: false,
          },
          data: [{
            yAxis: coordY.offbed,
          }]
        },
      });
    }
    if (this.state.apneaMarkPoint.length) {
      legendData.push({name: '呼吸暂停', icon: 'rec', textStyle: {color: '#fff'}});
      seriesData.push({
        data: [],
        type: 'line',
        id: 'apneaAxis',
        cusor: 'pointer',
        showSymbol: false,
        symbolSize: 8,
        name:'呼吸暂停',
        lineStyle: {
          color: lineColor.apnea,
          width: 1,
        },
        itemStyle: {
          color: lineColor.apnea,
        },
        markPoint: {
          symbol: 'pin',
          symbolSize: 15,
          data: this.state.apneaMarkPoint
        },
        markLine: {
          slient: true,
          label: {
            show: false,
          },
          data: [{
            yAxis: coordY.apnea,
          }]
        },
      })
    }
    const option = {
      animation: false,
      grid: {
        show: false,
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        formatter:function(params){
          var html = '';
          if(params.length>0){
            const titleValue = (params[0].axisValue / 1000).toFixed(3) + 's';         
            html += titleValue + '<br>';
            xAxisValue = params[0].axisValue;
            for ( var int = 0; int < params.length; int++) {
              html += params[int].marker + params[int].seriesName+':'+params[int].data[1]+'<br>';
            }
          }
          return html;
        }
      },
      legend: {
        top: 20,
        data: legendData,
      },
      xAxis: {
        type: 'value',
        nameTextStyle: {
          color: '#fff',
        },
        splitLine: {
          show: false,
        },
        axisTick: {
          lineStyle: {
            color: '#fff',
          }
        },
        axisLine: {
          lineStyle: {
            color: '#fff',
          }
        },
        axisLabel: {
          color: '#fff',
          formatter: function(value, index) {
            if ((value % 1000) === 0) {
              return (value / 1000).toFixed(0) + 's';
            }
            // return (value / 1000).toFixed(3) + 's';
            // const date = new Date(value);
            // const H = (date.getHours() < 10) ? ('0' + date.getHours()) : date.getHours();
            // const M = (date.getMinutes() < 10) ? ('0' + date.getMinutes()) : date.getMinutes();
            // const sec = (date.getSeconds() < 10) ? ('0' + date.getSeconds()) : date.getSeconds();
            // return H + ':' + M + ':' + sec;
          }
        },
        max: function(value) {
          return value.max;
        },
        splitNumber: 10,
      },
      yAxis: {
        type: 'value',
        nameTextStyle: {
          color: '#fff',
        },
        splitLine: {
          show: false,
        },
        axisTick: {
          lineStyle: {
            color: '#fff',
          }
        },
        axisLine: {
          lineStyle: {
            color: '#fff',
          }
        },
        axisLabel: {
          color: '#fff'
        },
        min: -2500,
        max: 2500,
        splitNumber: 10,
      },
      toolbox: {
        feature: {
          dataZoom: {
              yAxisIndex: 'none'
          },
          restore: {},
          saveAsImage: {}
        },
        iconStyle: {
          borderColor: '#fff',
        }
      },
      dataZoom: [
        {
          type: 'slider',
          start: this.state.dataZoomXStart,
          end: this.state.dataZoomXEnd,
          id: 'xAxis0',
          startValue: this.state.dataZoomXStartValue,
          endValue: this.state.dataZoomXEndValue,
          xAxisIndex: 0,
          handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '40%',
          textStyle: {
            color: '#fff',
          },
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          backgroundColor: 'rgba(152, 151, 151, 0.8)',
        },
        {
          type: 'slider',
          id: 'yAxis0',
          start: this.state.dataZoomYStart,
          end: this.state.dataZoomYEnd,
          startValue: 0,
          endValue: 0,
          yAxisIndex: 0,
          handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '40%',
          textStyle: {
            color: '#fff',
          },
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: 'rgba(0, 0, 0, 0.6)',
            shadowOffsetX: 2,
            shadowOffsetY: 2
          },
          backgroundColor: 'rgba(152, 151, 151, 0.8)',
        }
      ],
      series: seriesData,
    }
    return option;
  }

  onChartReadyCallback = (chartsInstance) => {
    const that = this;
    charts = chartsInstance;
    charts.on('datazoom', function(params) {
      if(params.batch && params.batch.length) {
        storeChartStatus.dataZoomXStart = null;
        storeChartStatus.dataZoomXEnd = null;
        storeChartStatus.dataZoomXStartValue = params.batch[0].startValue;
        storeChartStatus.dataZoomXEndValue = params.batch[0].endValue;
      }
      if (params.dataZoomId === 'xAxis0') {
        storeChartStatus.dataZoomXStart = params.start;
        storeChartStatus.dataZoomXEnd = params.end;
      }
      if (params.dataZoomId === 'yAxis0') {
        storeChartStatus.dataZoomYStart = params.start;
        storeChartStatus.dataZoomYEnd = params.end;
      }
    });
    charts.on('restore', function(params) {
      that.setState({
        dataZoomXStart: 0,
        dataZoomXEnd: 100,
        dataZoomXStartValue: 0,
        dataZoomXEndValue: 0,
        dataZoomYStart: 10,
        dataZoomYEnd: 90,
      });
      storeChartStatus = {
        dataZoomXStart: 0,
        dataZoomXEnd: 100,
        dataZoomXStartValue: 0,
        dataZoomXEndValue: 0,
        dataZoomYStart: 10,
        dataZoomYEnd: 90,
      }
    });
  }

  clickCharts = (e) => {
    if(this.state.markItem.length > 0) {
      const date = new Date(xAxisValue);
      const H = (date.getHours() < 10) ? ('0' + date.getHours()) : date.getHours();
      const M = (date.getMinutes() < 10) ? ('0' + date.getMinutes()) : date.getMinutes();
      const sec = (date.getSeconds() < 10) ? ('0' + date.getSeconds()) : date.getSeconds();
      const Msec = (date.getMilliseconds() < 100) ? ((date.getMilliseconds() < 10) ? ('00' + date.getMilliseconds()) : ('0' + date.getMilliseconds())) : (date.getMilliseconds());
      const markTime = H + ':' + M + ':' + sec + '.' + Msec + 'Z';
      this.setState({
        chartValue: markTime,
        dataZoomXStart: storeChartStatus.dataZoomXStart,
        dataZoomXEnd: storeChartStatus.dataZoomXEnd,
        dataZoomXStartValue: storeChartStatus.dataZoomXStartValue,
        dataZoomXEndValue: storeChartStatus.dataZoomXEndValue,
        dataZoomYStart: storeChartStatus.dataZoomYStart,
        dataZoomYEnd: storeChartStatus.dataZoomYEnd,
      });
      this.handleOk(xAxisValue);
    } else {
      this.modalWarning();
    }
  }

  modalWarning = () => {
    Modal.warning({
      title: '警告',
      content: '请先在事件面板选择事件类型',
    });
  }

  render() {
    return (
      <div id="drawPanel">
        {
          (this.props.plotChestData && (this.props.plotChestData.length > 0)) ? 
          <ReactEcharts
            onChartReady={this.onChartReadyCallback}
            option={this.getOption()}
            notMerge={true}
            lazyUpdate={true}
            className='echarts-for-echarts'
            style={{height: '500px'}}
            opts={{renderer: 'svg'}} 
            theme={"theme_name"}
          /> : <div className="placeholder">将文件或者文件夹拖入应用</div>
        }      
      </div>
    );
  }
}

export default DrawPanel;

